<?php

namespace mpend\modules\passport\models;

use Yii;
use mpend\models\User;

/**
 * 账号信息修改模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AccountForm extends \common\base\FormModel {

    /**
     * @var string 头像
     */
    public $username;

    /**
     * @var string 数据原型模型
     */
    public function getInstanceModelClass() {
        return Yii::$app->user->identityClass;
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            ['username', 'string', 'max' => 30],
            [['username'], '\common\validators\WordFilterValidator'],
            ['username', 'validateUsername'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'username' => '姓名',
        ];
    }

    /**
     * @inheritdoc
     */
    public function validateUsername($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = $this->getModel();
        $cache = $this->getCommonCache();
        $isValid = $cache->get('Security_' . $attribute . '_' . $model->id);
        if ($isValid !== true) {
            return $this->addError('更改帐号前需要进行安全验证');
        }
        $username = $this->$attribute;
        $user = User::findOne([
            'and',
            ['!=', 'id', $model->id],
            ['username' => $username],
        ]);
        if ($user) {
            return $this->addError($attribute, '当前帐号名称已被占用，请更换其他名称');
        }
    }

    /**
     * @inheritdoc
     */
    public function beforeValidate() {
        if (!parent::beforeValidate()) {
            return false;
        }
        if ($this->getIsNewRecord()) {
            return false;
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function setExtraAttributes($model) {
        $this->username = $model->username;
    }

    /**
     * @return User|null
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('');
        }
        /* @var $model User */
        $model = $this->getModel();
        if (!$model) {
            return $this->dumpError('用户不存在或者当前未登陆', false);
        }
        $attributes = array_filter($this->attributes);
        $model->setAttributes($attributes);
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                return $this->dumpError('帐号名称保存失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }
        return $model;
    }

}
